﻿using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace HealthCheck.Api.HealthChecks;

public class DiskStorageHealthCheck(IConfiguration configuration) : IHealthCheck
{
	private readonly string _drivePath = configuration["DiskHealthCheck:DrivePath"] ?? "C:";
	private readonly long _minimumFreeMegabytes = long.Parse(configuration["DiskHealthCheck:MinimumFreeMegabytes"] ?? "500");

	public Task<HealthCheckResult> CheckHealthAsync(
		HealthCheckContext context, 
		CancellationToken cancellationToken = default)
	{
		try
		{
			var drive = new DriveInfo(_drivePath);
            
			if (!drive.IsReady)
			{
				return Task.FromResult(
					HealthCheckResult.Unhealthy($"磁盘 {_drivePath} 不可用"));
			}
            
			var freeSpaceMegabytes = drive.AvailableFreeSpace / 1024 / 1024;
            
			if (freeSpaceMegabytes >= _minimumFreeMegabytes)
			{
				return Task.FromResult(
					HealthCheckResult.Healthy(
						$"磁盘空间充足: {freeSpaceMegabytes}MB 可用 (要求: {_minimumFreeMegabytes}MB)"));
			}
            
			return Task.FromResult(
				HealthCheckResult.Degraded(
					$"磁盘空间不足: {freeSpaceMegabytes}MB 可用 (要求: {_minimumFreeMegabytes}MB)"));
		}
		catch (Exception ex)
		{
			return Task.FromResult(
				HealthCheckResult.Unhealthy($"磁盘检查失败: {ex.Message}"));
		}
	}
}
